//
//  RManager.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/19.
//

import UIKit
import VTO2Lib

class RManager {

    static let manager = RManager()
    // 当前链接设备
    var currentDevice: VTDevice?
    // 当前链接设备信息
    var info: VTO2Info?
    
    /// 大小设备
    var isBig = true
    
    // 当前展示的历史设备
    var currentHistoryDevice: VTDevice?
    
    // 是否正在上传
    var uploading = false
    var needUpdateData = [RModel]()
    
    // 实时上传的数据
    var onlineUploadData = [RModel]()
    
    var timer: Timer?
    var timeIntervel = 0
    
    /// 实时上传数据
    @objc func startOnlineUpload() {
        
        if currentDevice == nil {
            return
        }
        
        if CacheManager.manager.containsObject(forKey: OnlineUploadConfig) == false {
            return
        }
        
        guard let config = CacheManager.manager.getValueForKey(OnlineUploadConfig) as? UploadConfig else { return }
        
        if config.auto == false {
            return
        }
        
        timeIntervel = Int(config.interval) ?? 3
        
        // 不停的运行
        if timer == nil {
            self.timer = Timer.scheduledTimer(timeInterval: TimeInterval.init(timeIntervel), target: self, selector: #selector(self.startOnlineUpload), userInfo: nil, repeats: true)
            self.timer!.fireDate = Date.distantPast
        }else {
            // 修改了时间
            if self.timer?.timeInterval != TimeInterval(timeIntervel) {
                self.timer?.fireDate = Date.distantFuture
                self.timer = Timer.scheduledTimer(timeInterval: TimeInterval.init(timeIntervel), target: self, selector: #selector(self.startOnlineUpload), userInfo: nil, repeats: true)
                self.timer!.fireDate = Date.distantPast
            }
        }
        
        var array = [RModel]()
        // 找到还未上传的
        for obj in onlineUploadData {
            if obj.hadUpload == false {
                array.append(obj)
                obj.hadUpload = true
            }
        }
        
        // 上传
        if array.count > 0 {
            self.uploadNetwork(param: self.encapsulationParam(array: array, isHistory: false), isHistory: false)
        }
        
    }
    
    func uploadHistoryListToCloud(isHistory: Bool) {
        if needUpdateData.count > 0 {
            uploading = true
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
            // 防止数据过多，采用截取上传方式
            if needUpdateData.count > 20 {
                let array = Array(needUpdateData.prefix(20))
                needUpdateData = Array(needUpdateData[21...needUpdateData.count - 1])
                self.uploadNetwork(param: self.encapsulationParam(array: array, isHistory: isHistory), isHistory: isHistory)
            }else {
                // 数据少，直接上传
                self.uploadNetwork(param: self.encapsulationParam(array: self.needUpdateData, isHistory: isHistory), isHistory: isHistory)
                self.needUpdateData.removeAll()
            }
            
        }else {
            uploading = false
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
        }
    }
    
    /// 转化模型
    func encapsulationParam(array: [RModel], isHistory: Bool) -> [[String: Any]] {
        var update = [[String: Any]]()
//        for obj in array {
//            let dic = obj.toDictionary()
//            update.append(dic)
//        }
        if isHistory == true {
            for obj in array {
                var dic = obj.toDictionary()
                dic.removeValue(forKey: "hr")
                dic["pr"] = obj.hr
                update.append(dic)
            }
        }else {
            // sn,pr，spo2,timeStamp，deviceName
            for obj in array {
                let dic = [
                    "sn": obj.sn ?? "",
                    "pr": obj.hr ?? 0,
                    "timeStamp": obj.timeStamp ?? 0,
                    "deviceName": obj.deviceName ?? ""
                ] as [String: Any]
                update.append(dic)
            }
        }
        return update
    }
    
    func uploadNetwork(param: [[String: Any]], isHistory: Bool) {
        
        let service = FBYHomeService.init()
        
        var url = ""
        if isHistory {
            if let config = CacheManager.manager.getValueForKey(HistoryUploadConfig) as? UploadConfig {
                url = config.apiUrl
            }
        }else {
            if let config = CacheManager.manager.getValueForKey(OnlineUploadConfig) as? UploadConfig {
                url = config.apiUrl
            }
        }
        
        if url == "" {
            self.uploading = false
            self.needUpdateData.removeAll()
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
            return
        }
        
        self.uploading = true
        NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
        service.searchMessage("post", andWithDic: param, andUrl: url) { result in
            
            print("----------------------uploadSuccess:\(param.count)个----------------------")
            if isHistory == true {
                self.uploadHistoryListToCloud(isHistory: isHistory)
            }
            self.uploading = false
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
            
        } andFailure: { error in
            
            print("----------------------uploadFail----------------------")
            if isHistory == true {
                self.uploadHistoryListToCloud(isHistory: isHistory)
            }
            self.uploading = false
            NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: UploadState), object: nil)
        }
        
    }
    
    /// GCD实现定时器
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - handler: 事件
    ///   - needRepeat: 是否重复
    func dispatchTimer(timeInterval: Double, handler: @escaping (DispatchSourceTimer?) -> Void, needRepeat: Bool) {
        
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            DispatchQueue.main.async {
                if needRepeat {
                    handler(timer)
                } else {
                    timer.cancel()
                    handler(nil)
                }
            }
        }
        timer.resume()
        
    }
    
}
